package controllers

import (
	"encoding/json"
	"errors"

	md "gitee.com/countpoison/youbei/models"

	"github.com/segmentio/ksuid"
)

// Ftpadd ...
func (c *MainController) Ftpadd() {
	ob := new(md.RemoteStorage)
	c.APIReturn(500, "数据解析失败", json.Unmarshal(c.Ctx.Input.RequestBody, ob))
	ob.ID = ksuid.New().String()
	c.APIReturn(500, "添加失败", ob.Add())
	c.APIReturn(200, "添加成功", ob)
}

// Ftpdelete ...
func (c *MainController) Ftpdelete() {
	id := c.Ctx.Input.Param(":id")
	ob := new(md.RemoteStorage)
	ob.ID = id
	c.APIReturn(500, "删除失败", ob.Delete())
	c.APIReturn(200, "删除成功", nil)
}

// Ftplist ...
func (c *MainController) Ftplist() {
	page, _ := c.GetInt("page")
	limit, _ := c.GetInt("count")
	RemoteStorages := []md.RemoteStorage{}
	xs := md.Localdb().Desc("created")
	if limit > 0 {
		xs = xs.Limit(limit, limit*(page-1))
	}
	c.APIReturn(500, "获取列表失败", xs.Find(&RemoteStorages))
	ftps := md.RemoteStorage{}
	title, err := md.Localdb().Count(&ftps)
	c.APIReturn(500, "获取总数失败", err)
	rep := map[string]interface{}{"count": title, "data": RemoteStorages}
	c.APIReturn(200, "获取列表成功", &rep)
}

// Ftpfind 查询远程存储 单
func (c *MainController) Ftpfind() {
	rs := new(md.RemoteStorage)
	bol, err := md.Localdb().ID(c.Ctx.Input.Param(":id")).Get(rs)
	c.APIReturn(500, "找不到该远程存储", err)
	if !bol {
		c.APIReturn(500, "找不到该远程存储", errors.New("not found"))
	}
	c.APIReturn(200, "获取成功", rs)
}

// Ftpupdate 查询远程存储 单
func (c *MainController) Ftpupdate() {
	id := c.Ctx.Input.Param(":id")
	if id == "" {
		c.APIReturn(500, "id不能为空", errors.New("id不能为空"))
	}
	rs := new(md.RemoteStorage)
	c.APIReturn(500, "解析失败", json.Unmarshal(c.Ctx.Input.RequestBody, rs))
	c.APIReturn(500, "修改失败", rs.Update())
	c.APIReturn(200, "修改成功", nil)
}

// Rloglist 查询远程存储 单
func (c *MainController) Rloglist() {
	tid := c.Ctx.Input.Param(":id")
	page, _ := c.GetInt("page")
	limit, _ := c.GetInt("count")
	rlogs, err := md.RlogAll(tid, page, limit)
	c.APIReturn(500, "获取列表失败", err)
	title := int64(0)
	if tid == "" {
		title, err = md.Localdb().Count(new(md.Rlog))
	} else {
		title, err = md.Localdb().Where("tid=?", tid).Count(new(md.Rlog))
	}
	c.APIReturn(500, "获取总数失败", err)
	rep := map[string]interface{}{"count": title, "data": rlogs}
	c.APIReturn(200, "获取列表成功", &rep)
}
